package com.lemon.cloud.datascope.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.lemon.cloud.admin.feign.DataScopeFeign;
import com.lemon.cloud.comm.model.ResultMsg;
import com.lemon.cloud.comm.po.RoleApplication;
import com.lemon.cloud.security.model.SecurityUser;
import com.lemon.cloud.security.util.SecurityUtils;
import com.lemon.cloud.core.utils.SpringContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.SelectExpressionItem;
import net.sf.jsqlparser.statement.select.SubSelect;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName DataScopeHelper
 * @Description 数据权限方式二：代码方式
 * @Author HuangDS
 * @Date 2022/4/2 14:54
 **/
public class DataScopeHelper {

    private final static String SYS_ROLE = "sys_role";

    private final static String ID_COLUMN = "id";

    private final static String CODE_COLUMN = "code";

    private final static String AND = "and ";

    /**
     * 根据权限相关配置生成相关的SQL 语句
     * 适用于，sys_org 表和当前过滤表在同一个数据库
     *
     * @param tableAlias
     * @param columnName
     * @return
     */
    public static String authOrgCommJdbc(String tableAlias, String columnName) {
        //权限查询
        SecurityUser user = SecurityUtils.getUser();
        if (!validUser(user)) {
            return StrUtil.EMPTY;
        }
        InExpression in = new InExpression();
        in.setLeftExpression(buildColumn(tableAlias, columnName));
        SubSelect subSelect = new SubSelect();
        PlainSelect select = new PlainSelect();
        select.setSelectItems(Collections.singletonList(new SelectExpressionItem(new Column(ID_COLUMN))));
        select.setFromItem(new Table(SYS_ROLE));
        select.setWhere(getInExpressionByCode(null, CODE_COLUMN, SecurityUtils.getRoleCode()));
        subSelect.setSelectBody(select);
        in.setRightItemsList(subSelect);
        return AND + in.toString();
    }

    /**
     * mybatis plus 过滤
     *
     * @param queryWrapper
     * @param column
     * @return
     */
    public static <E, A> void authOrgMplus(LambdaQueryWrapper<E> queryWrapper, SFunction<E, A> column) {
        try {
            SecurityUser user = SecurityUtils.getUser();
            if (!validUser(user)) {
                return;
            }
            DataScopeFeign feign = SpringContextHolder.getBean(DataScopeFeign.class);
            //todo 2023修改数据权限
            ResultMsg<List<RoleApplication>> roleList = feign.getDSList(SecurityUtils.getRoleCode());
            if (CollectionUtil.isNotEmpty(roleList.getData())) {
                queryWrapper.and(w -> w.in(column, roleList.getData()));
            } else {
                queryWrapper.and(w -> w.last(" 1 = 0"));
            }
        } catch (BeansException e) {
            e.getLocalizedMessage();
        }
    }


    public static Expression getRightExpressionById(String tableAlias, String columnName, List<Long> dataList) {
        InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(buildColumn(tableAlias, columnName));
        final ExpressionList itemsList = new ExpressionList();
        final List<Expression> inValues = new ArrayList<>(dataList.size());
        for (Long id : dataList) {
            inValues.add(new LongValue(id));
        }
        itemsList.addExpressions(inValues);
        inExpression.setRightItemsList(itemsList);
        return inExpression;
    }

    public static InExpression getInExpressionByCode(String tableAlias, String columnName, List<String> dataCodeList) {
        InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(buildColumn(tableAlias, columnName));
        final ExpressionList itemsList = new ExpressionList();
        final List<Expression> inValues = new ArrayList<>(dataCodeList.size());
        for (String code : dataCodeList) {
            inValues.add(new StringValue(code));
        }
        itemsList.addExpressions(inValues);
        inExpression.setRightItemsList(itemsList);
        return inExpression;
    }

    public static Column buildColumn(String tableAlias, String columnName) {
        if (StringUtils.isNotEmpty(tableAlias)) {
            columnName = tableAlias + StrUtil.DOT + columnName;
        }
        return new Column(columnName);
    }

    private static Boolean validUser(SecurityUser user) {
        if (ObjectUtil.isNull(user) ||
                ObjectUtil.isNull(user.getSysUser()) ||
                ObjectUtil.isNull(user.getSysUser().getId())) {
            return false;
        }
        return true;
    }
}
